package com.kinghood.productcenter.service.product.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kinghood.infrastructure.api.authority.DirectionRemoteVO;
import com.kinghood.infrastructure.api.authority.DirectionReqRemoteDTO;
import com.kinghood.infrastructure.api.authority.UserRemoteVo;
import com.kinghood.infrastructure.model.KingHoodException;
import com.kinghood.infrastructure.model.KingHoodExceptionUtil;
import com.kinghood.infrastructure.model.constant.CommonConstants;
import com.kinghood.infrastructure.model.dto.StatusRemarkReqDTO;
import com.kinghood.infrastructure.util.base.IdGenUtil;
import com.kinghood.infrastructure.util.UserUtil;
import com.kinghood.productcenter.common.api.authority.SystemDirectionRemote;
import com.kinghood.productcenter.common.api.authority.UserRemote;
import com.kinghood.productcenter.common.model.constants.ProductConstant;
import com.kinghood.productcenter.common.model.dao.base.*;
import com.kinghood.productcenter.common.model.dao.product.*;
import com.kinghood.productcenter.common.model.dto.base.AttributeCodesReqDTO;
import com.kinghood.productcenter.common.model.dto.base.AttributeReqDTO;
import com.kinghood.productcenter.common.model.dto.base.ListProductQueryDTO;
import com.kinghood.productcenter.common.model.dto.product.*;
import com.kinghood.productcenter.common.model.dto.restcloud.GetProductInfoReqDTO;
import com.kinghood.productcenter.common.model.dto.sku.GetSkuRelateIdDTO;
import com.kinghood.productcenter.common.model.dto.sku.ProductSkuReqDTO;
import com.kinghood.productcenter.common.model.enums.product.BusinessLogOperateEnum;
import com.kinghood.productcenter.common.model.enums.product.ProductSkuStatusEnums;
import com.kinghood.productcenter.common.model.enums.product.ProductStatusEnums;
import com.kinghood.productcenter.common.model.vo.base.AttributeNameVO;
import com.kinghood.productcenter.common.model.vo.base.AttributeValueVO;
import com.kinghood.productcenter.common.model.vo.base.BaseAttributeVO;
import com.kinghood.productcenter.common.model.vo.product.ProductListVO;
import com.kinghood.productcenter.common.model.vo.product.GetUserSearchSettingVO;
import com.kinghood.productcenter.common.model.vo.product.ProductConfigVO;
import com.kinghood.productcenter.common.model.vo.product.ProductLabelVO;
import com.kinghood.productcenter.common.model.vo.product.SearchSettingVO;
import com.kinghood.productcenter.common.utils.UserNameUtil;
import com.kinghood.productcenter.dao.base.*;
import com.kinghood.productcenter.dao.product.ProductBaseMapper;
import com.kinghood.productcenter.service.async.IAsyncBusinessLogService;
import com.kinghood.productcenter.service.base.IBaseAttributeService;
import com.kinghood.productcenter.service.base.IBaseLabelItemService;
import com.kinghood.productcenter.service.base.IBaseSupplierService;
import com.kinghood.productcenter.service.base.impl.BaseProductTemplateServiceImpl;
import com.kinghood.productcenter.service.product.*;
import com.kinghood.productcenter.service.product.handler.ProductBaseHandler;
import com.kinghood.sharding.model.KingHoodPageUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品款式基础表 服务实现类
 * </p>
 *
 * @author KingHood
 * @since 2023-12-20
 */
@RequiredArgsConstructor
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class ProductBaseServiceImpl extends ServiceImpl<ProductBaseMapper, ProductBaseDO> implements IProductBaseService {

    private final IBaseAttributeService baseAttributeService;
    private final IProductAttributeService productAttributeService;
    private final IProductSkuBaseService productSkuBaseService;
    private final IProductSkuExtrasBaseService productSkuExtrasBaseService;
    private final IProductSkuSupplierBaseService productSkuSupplierBaseService;
    private final BaseBrandMapper brandMapper;
    private final BaseGoodsMapper goodsMapper;
    private final BaseCategoryMapper categoryMapper;
    private final BaseAttributeMapper attributeMapper;
    private final BaseAttributeLimitMapper baseAttributeLimitMapper;
    private final BaseAttributeValueMapper attributeValueMapper;
    private final IBaseSupplierService supplierService;
    private final IProductSkuLabelRelateService productSkuLabelRelateService;
    private final IBaseLabelItemService baseLabelItemService;
    private final UserRemote userRemote;
    private final IAsyncBusinessLogService asyncBusinessLogService;
    private final SystemDirectionRemote directionRemote;
    private final BaseProductTemplateServiceImpl productTemplateService;
    private final  IUserSearchSettingService userSearchSettingService;

    /**
     * 款式列表
     *
     * @param param 参数
     * @author jp
     * @date 2023/12/22
     */
    @Override
    public Page<ProductListVO> listProduct(ListProductQueryDTO param) {
        param.processingData();
        Page<ProductListVO> result = this.baseMapper.listProduct(KingHoodPageUtil.getPage(param, param), param);
        result.getRecords().stream().forEach(i -> {
            if (!StringUtils.isEmpty(i.getHdPicture())) {
                i.setPicture(i.getHdPicture());
            } else if (!StringUtils.isEmpty(i.getOperationPicture())) {
                i.setPicture(i.getOperationPicture());
            } else if (!StringUtils.isEmpty(i.getHandPicture())) {
                i.setPicture(i.getHandPicture());
            } else if (!StringUtils.isEmpty(i.getFactoryPicture())) {
                i.setPicture(i.getFactoryPicture());
            }
            if (!StringUtils.isEmpty(i.getPicture())) {
                String[] split = i.getPicture().split(",");
                if (split.length > 0) {
                    i.setPicture(split[0]);
                }
            }
            i.setStatusTxt(ProductStatusEnums.getNameByType(i.getStatus()));
        });

        Set<Long> userIdList = new HashSet<>();
        for (ProductListVO record : result.getRecords()) {
            userIdList.add(record.getCreateUserId());
            userIdList.add(record.getUpdateUserId());
        }
        userIdList.remove(null);
        if (!CollectionUtils.isEmpty(userIdList)) {
            Map<Long, UserRemoteVo> userMap = userRemote.getUserByIds(new ArrayList<Long>(userIdList));
            for (ProductListVO record : result.getRecords()) {
                record.setCreateUserName(UserNameUtil.getName(record.getCreateUserId(), userMap));
                record.setUpdateUserName(UserNameUtil.getName(record.getUpdateUserId(), userMap));
            }
        }
        return result;
    }

    @Override
    public Long addProduct(ProductReqDTO in) {

        Long count = new LambdaQueryChainWrapper<>(this.getBaseMapper())
                .eq(ProductBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .eq(ProductBaseDO::getStyleNumber, in.getProductBase().getStyleNumber())
                .count();
        KingHoodExceptionUtil.trueThrows(count > 0, "款号已存在");

        List<String> allSkuCode = in.getSkuList().stream().filter(Objects::nonNull)
                .map(ProductSkuReqDTO::getSkuCode)
                .filter(Objects::nonNull).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(allSkuCode)){
            Long skuCount = new LambdaQueryChainWrapper<>(productSkuBaseService.getBaseMapper())
                    .eq(ProductSkuBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .in(ProductSkuBaseDO::getSkuCode, allSkuCode)
                    .count();
            KingHoodExceptionUtil.trueThrows(skuCount > 0, "SKU编码已存在");
        }

        ProductBaseDO productBaseDO = new ProductBaseDO();
        BeanUtils.copyProperties(in, productBaseDO);
        productBaseDO.setId(IdGenUtil.get().nextId());
        productBaseDO.setStyleNumber(in.getProductBase().getStyleNumber());
        productBaseDO.setStyleName(in.getProductBase().getStyleName());
        productBaseDO.setStatus(in.getProductBase().getStatus());
        productBaseDO.setProductTemplateId(in.getProductTemplateId());
        productBaseDO.setCreateTime(LocalDateTime.now());
        productBaseDO.setUpdateTime(LocalDateTime.now());
        productBaseDO.setCreateUserId(UserUtil.getUserId());
        productBaseDO.setUpdateUserId(UserUtil.getUserId());
        this.save(productBaseDO);

        //所有属性
        Map<String, BaseAttributeVO> attributeVOMap = getBaseAttributeMap();

        if (!CollectionUtils.isEmpty(in.getProductBase().getAttributes())) {
            Map<String, BaseAttributeVO> finalAttributeVOMap = attributeVOMap;
            ArrayList<ProductAttributeDO> attributeList = new ArrayList<>();
            in.getProductBase().getAttributes().forEach((k, y) -> {
                if (ProductConstant.NO_ATTRIBUTE_LIST.contains(k)) {
                    return;
                }
                BaseAttributeVO baseAttributeVO = finalAttributeVOMap.get(k);
                KingHoodExceptionUtil.isNull(baseAttributeVO, "属性" + k + "不存在");

                ProductAttributeDO productAttributeDO = new ProductAttributeDO();
                productAttributeDO.setId(IdGenUtil.getId());
                productAttributeDO.setProductId(productBaseDO.getId());
                productAttributeDO.setBusinessId(productBaseDO.getId());
                productAttributeDO.setBusinessType(ProductAttributeDO.BUSINESS_TYPE_PRODUCT);
                productAttributeDO.setAttributeId(baseAttributeVO.getId());
                productAttributeDO.setAttributeCode(baseAttributeVO.getAttributeCode());
                productAttributeDO.setValue(ProductBaseHandler.handleAttributeValue(y));
                productAttributeDO.setValueFind(ProductBaseHandler.handleAttributeValueFind(productAttributeDO.getValue()));
                productAttributeDO.setValueType(baseAttributeVO.getValueType());
                productAttributeDO.setCreateTime(LocalDateTime.now());
                productAttributeDO.setCreateTime(LocalDateTime.now());
                productAttributeDO.setCreateUserId(UserUtil.getUserId());
                attributeList.add(productAttributeDO);
            });
            productAttributeService.saveBatch(attributeList);
        }

        List<ProductSkuBaseDO> skuList = productSkuBaseService.addSku(in.getSkuList(), productBaseDO.getId(), attributeVOMap, Collections.emptyMap());
        Map<String, ProductSkuBaseDO> skuMap = skuList.stream()
                .filter(Objects::nonNull)
                .filter(x->Objects.nonNull(x.getSkuCode()))
                .collect(Collectors.toMap(ProductSkuBaseDO::getSkuCode, v -> v, (k1, k2) -> k2));
        productSkuExtrasBaseService.addSkuExtras(in.getSkuExtrasList(), productBaseDO.getId(), skuMap, attributeVOMap, Collections.emptyMap());
        productSkuSupplierBaseService.addSkuSupplier(in.getSkuSupplierList(), productBaseDO.getId(), skuMap, attributeVOMap, Collections.emptyMap());

        log.info("商品保存==》in:{};;;attributeVOMap:{}", in, attributeVOMap);

        asyncBusinessLogService.addLog(null, productBaseDO.getId(), null,
                BusinessLogOperateEnum.ADD.getType(), UserUtil.getUserId());

        return productBaseDO.getId();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long updateProduct(ProductReqDTO in) {

        ProductDTO oldProduct = this.getProduct(in.getProductBase().getId());
        KingHoodExceptionUtil.isNull(oldProduct, "商品不存在");

        Long count = new LambdaQueryChainWrapper<>(this.getBaseMapper())
                .eq(ProductBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .eq(ProductBaseDO::getStyleNumber, in.getProductBase().getStyleNumber())
                .notIn(ProductBaseDO::getId, in.getProductBase().getId())
                .count();
        KingHoodExceptionUtil.trueThrows(count > 0, "款号已存在");


        List<String> skuCodeList = productSkuBaseService.getSkuCodeList(in.getProductBase().getId());
        List<String> allSkuCode = in.getSkuList().stream().map(ProductSkuReqDTO::getSkuCode).filter(Objects::nonNull).collect(Collectors.toList());
        if(!CollectionUtils.isEmpty(allSkuCode)){
            Long skuCount = new LambdaQueryChainWrapper<>(productSkuBaseService.getBaseMapper())
                    .eq(ProductSkuBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .in(ProductSkuBaseDO::getSkuCode, allSkuCode)
                    .notIn(!CollectionUtils.isEmpty(skuCodeList),ProductSkuBaseDO::getSkuCode, skuCodeList)
                    .count();
            KingHoodExceptionUtil.trueThrows(skuCount > 0, "SKU编码已存在");
        }

        // 模板的属性，这里约束删除的属性范围
//        List<String> attributeCode = in.getAttributeCode();
//        List<Long> templateAttributeIdList = baseAttributeService.getAttributeIdList(attributeCode);
        // 模板，未填的时候前端不传递，导致判断失误
        if(Objects.isNull(in.getProductTemplateId())){
            in.setProductTemplateId(oldProduct.getProductTemplateId());
        }
        List<ProductTemplateAttributeDTO> attributeList= productTemplateService.getBaseMapper().getAttributeListByTemplateId(in.getProductTemplateId());
        List<Long> templateAttributeIdList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(attributeList)){
            templateAttributeIdList = attributeList.stream().map(BaseProductTemplateGitemDO::getAttributeId).collect(Collectors.toList());
        }

        // 获取旧的数据，对于sku编码相同的需要寻找回
        List<AttributeByProductIdDTO> oldAttributeList = productAttributeService.getAttributeByProductId(in.getProductBase().getId());
        Map<String, Long> skuCodeMap = productSkuBaseService.getSkuByProductId(in.getProductBase().getId());
        Map<String, Long> oldExtrasMap = productSkuExtrasBaseService.getExtrasByProductId(in.getProductBase().getId());
        Map<String, Long> oldSupplierMap = productSkuSupplierBaseService.getSupplierByProductId(in.getProductBase().getId());

        // 针对剔除sku的数据需要清除
        List<Long> noDeleteSkuIdList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(in.getSkuList())){
            Map<String, Long> finalSkuCodeMap = skuCodeMap;
            noDeleteSkuIdList = in.getSkuList().stream().map(sku -> finalSkuCodeMap.get(sku.getSkuCode()))
                    .filter(Objects::nonNull).collect(Collectors.toList());
        }

        // 删除的sku
        productAttributeService.deleteSkuAttribute(in.getProductBase().getId(),noDeleteSkuIdList);
        // 删除旧数据，非模板的属性不能清理
        productAttributeService.deleteByProductId(in.getProductBase().getId(),templateAttributeIdList,null, null);
        productSkuBaseService.deleteByProductId(in.getProductBase().getId());
        productSkuExtrasBaseService.deleteByProductId(in.getProductBase().getId(), null);
        productSkuSupplierBaseService.deleteByProductId(in.getProductBase().getId(), null);

        ProductBaseDO productBaseDO = new ProductBaseDO();
        BeanUtils.copyProperties(oldProduct, productBaseDO);
        productBaseDO.setId(oldProduct.getProductBase().getId());
        productBaseDO.setStyleNumber(oldProduct.getProductBase().getStyleNumber());
        BeanUtils.copyProperties(in, productBaseDO);
        productBaseDO.setProductTemplateId(in.getProductTemplateId());
        productBaseDO.setStyleName(in.getProductBase().getStyleName());
        productBaseDO.setStatus(in.getProductBase().getStatus());
        productBaseDO.setUpdateTime(LocalDateTime.now());
        productBaseDO.setUpdateUserId(UserUtil.getUserId());
        this.updateById(productBaseDO);

        //所有属性
        Map<String, BaseAttributeVO> attributeVOMap = getBaseAttributeMap();

        if (!CollectionUtils.isEmpty(in.getProductBase().getAttributes())) {
            productAttributeService.saveList(in.getProductBase().getAttributes(), productBaseDO.getId(), productBaseDO.getId(),
                    ProductAttributeDO.BUSINESS_TYPE_PRODUCT, attributeVOMap);
        }
        // 当存在旧sku，需要id保持不变
        List<ProductSkuBaseDO> skuList = productSkuBaseService.addSku(in.getSkuList(), productBaseDO.getId(), attributeVOMap,skuCodeMap);
        Map<String, ProductSkuBaseDO> skuMap = skuList.stream()
                .filter(Objects::nonNull)
                .filter(x->Objects.nonNull(x.getSkuCode()))
                .collect(Collectors.toMap(ProductSkuBaseDO::getSkuCode, v -> v, (k1, k2) -> k2));
        productSkuExtrasBaseService.addSkuExtras(in.getSkuExtrasList(), productBaseDO.getId(), skuMap, attributeVOMap,oldExtrasMap);
        productSkuSupplierBaseService.addSkuSupplier(in.getSkuSupplierList(), productBaseDO.getId(), skuMap, attributeVOMap,oldSupplierMap);

        log.info("商品修改==》in:{};;;attributeVOMap:{}", in, attributeVOMap);

        UpdateProductLogDTO logInfo = new UpdateProductLogDTO();
        logInfo.setUserId(UserUtil.getUserId());
        logInfo.setIn(in);
        logInfo.setOldSkuCodeMap(skuCodeMap);
        logInfo.handleOldAttribute(oldAttributeList);
        logInfo.setOldProductDTO(oldProduct);

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization(){
            @Override
            public void afterCommit() {
                asyncBusinessLogService.addUpdateProductLog(logInfo,false);
            }
        });

        return productBaseDO.getId();
    }


    private Map<String, BaseAttributeVO> getBaseAttributeMap() {
        List<BaseAttributeVO> attributeVOList = baseAttributeService.getAllAttribute();
        Map<String, BaseAttributeVO> attributeVOMap = new HashMap<>(1);
        if (!CollectionUtils.isEmpty(attributeVOList)) {
            attributeVOMap = attributeVOList.stream()
                    .collect(Collectors.toMap(BaseAttributeVO::getAttributeCode, v -> v, (k1, k2) -> k2));
        }
        return attributeVOMap;
    }

    @Override
    public ProductDTO getProduct(Long id) {

        BaseProductDTODO product = this.getBaseMapper().getProduct(id);
        KingHoodExceptionUtil.isNull(product, "商品不存在");
        product.handNull();

        List<ProductAttributeDO> attributeList = productAttributeService.getByProductId(id,null);
        Map<String, List<ProductAttributeDO>> attributeMap = attributeList.stream()
                .collect(Collectors.groupingBy(k ->  k.getBusinessId() + "-" + k.getBusinessType()));

        ProductDTO res = new ProductDTO();
        BeanUtils.copyProperties(product, res);

        res.setProductBase(ProductBaseHandler.getProductBase(product, attributeMap));
        res.setSkuList(ProductBaseHandler.getSkuList(product, attributeMap));
        res.setSkuExtrasList(ProductBaseHandler.getSkuExtrasList(product, attributeMap));
        res.setSkuSupplierList(ProductBaseHandler.getSkuSupplierList(product, attributeMap));

        return res;
    }


    @Override
    public BaseProductDaoDTO getBaseProductDao() {
        BaseProductDaoDTO dao = new BaseProductDaoDTO();

        ArrayList<CompletableFuture> list = new ArrayList<>();
        CompletableFuture<Void> f1 = CompletableFuture.runAsync(() -> {
            List<ProductBaseDO> productBaseList = new LambdaQueryChainWrapper<>(this.getBaseMapper())
                    .eq(ProductBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .list();
            if (!CollectionUtils.isEmpty(productBaseList)) {
                Map<String, Long> map = productBaseList.stream()
                        .collect(Collectors.toMap(ProductBaseDO::getStyleNumber, ProductBaseDO::getId, (k1, k2) -> k2));
                List<String> styleList = productBaseList.stream().map(x -> x.getStyleNumber()).collect(Collectors.toList());
                dao.setStyleList(styleList);
                dao.setStyleMap(map);
            }
        });
        list.add(f1);
        CompletableFuture<Void> f2 = CompletableFuture.runAsync(() -> {
            List<String> skuCodeList = productSkuBaseService.getSkuCodeList(null);
            dao.setSkuCodeList(skuCodeList);
        });
        list.add(f2);
        CompletableFuture<Void> f3 = CompletableFuture.runAsync(() -> {
            List<BaseAttributeDO> attributeList = new LambdaQueryChainWrapper<>(attributeMapper)
                    .eq(BaseAttributeDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseAttributeDO::getStatus, CommonConstants.ENABLE).list();
            dao.setAttributeList(attributeList);
        });
        list.add(f3);
        CompletableFuture<Void> f4 = CompletableFuture.runAsync(() -> {
            List<BaseBrandDO> brandList = new LambdaQueryChainWrapper<>(brandMapper)
                    .eq(BaseBrandDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseBrandDO::getStatus, CommonConstants.ENABLE).list();
            if (!CollectionUtils.isEmpty(brandList)) {
                Map<String, Long> map = brandList.stream()
                        .collect(Collectors.toMap(BaseBrandDO::getBrandName, BaseBrandDO::getId, (k1, k2) -> k2));
                dao.setBrandMap(map);
            }
        });
        list.add(f4);
        CompletableFuture<Void> f5 = CompletableFuture.runAsync(() -> {
            List<BaseGoodsDO> goodsList = goodsMapper.getBottomList();
            if (!CollectionUtils.isEmpty(goodsList)) {
                Map<String, Long> map = goodsList.stream()
                        .collect(Collectors.toMap(BaseGoodsDO::getGoodsName, BaseGoodsDO::getId, (k1, k2) -> k2));
                dao.setGoodsMap(map);
            }
        });
        list.add(f5);
        CompletableFuture<Void> f6 = CompletableFuture.runAsync(() -> {
            List<BaseCategoryDO> categoryList = categoryMapper.getBottomList();
            if (!CollectionUtils.isEmpty(categoryList)) {
                Map<String, Long> map = categoryList.stream()
                        .collect(Collectors.toMap(BaseCategoryDO::getCategoryName, BaseCategoryDO::getId, (k1, k2) -> k2));
                dao.setCategoryMap(map);
            }
        });
        list.add(f6);
        CompletableFuture<Void> f7 = CompletableFuture.runAsync(() -> {
            List<BaseSupplierDO> supplierList = new LambdaQueryChainWrapper<>(supplierService.getBaseMapper())
                    .eq(BaseSupplierDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseSupplierDO::getStatus, CommonConstants.ENABLE).list();
            if (!CollectionUtils.isEmpty(supplierList)) {
                Map<String, Long> map = supplierList.stream()
                        .collect(Collectors.toMap(BaseSupplierDO::getSupplierName, BaseSupplierDO::getId, (k1, k2) -> k2));
                dao.setSupplierMap(map);
            }
        });
        list.add(f7);
        CompletableFuture<Void> f8 = CompletableFuture.runAsync(() -> {
            List<BaseAttributeLimitDO> attributeLimitDOList = new LambdaQueryChainWrapper<>(baseAttributeLimitMapper)
                    .eq(BaseAttributeLimitDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .list();
            dao.setAttributeLimitList(attributeLimitDOList);
        });
        list.add(f8);
        CompletableFuture<Void> f9 = CompletableFuture.runAsync(() -> {
            List<BaseAttributeValueDO> attributeValueList = new LambdaQueryChainWrapper<>(attributeValueMapper)
                    .eq(BaseAttributeValueDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseAttributeValueDO::getStatus, CommonConstants.ENABLE).list();
            dao.setAttributeValueList(attributeValueList);
        });
        list.add(f9);
        CompletableFuture.allOf(list.toArray(new CompletableFuture[]{})).join();

        return dao;
    }

    @Override
    public List<Map<String, String>> handleImportData(List<Map<Integer, String>> list, Map<Integer, ProductExcelAttributeDTO> headCodeMap, BaseProductDaoDTO dao) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<Map<String, String>> res = new ArrayList<>();
        for (Map<Integer, String> data : list) {
            Map<String, String> rowMap = new HashMap<>();
            data.forEach((key, value) -> {
                ProductExcelAttributeDTO code = headCodeMap.get(key);
                KingHoodExceptionUtil.isNull(code, "excel解析异常：" + data.toString());
                if (Objects.equals(code.getIsAttribute(), Boolean.TRUE)) {
                    ExcelDataInfoDTO one = new ExcelDataInfoDTO();
                    one.setIndex(key);
                    one.setValue(value);
                    one.setAttributeId(code.getAttributeId());
                    one.setAttributeCode(code.getAttributeCode());
                    one.setValueCode(code.getValueCode());
                    one.setValueType(code.getValueType());
                    one.setIsMultipleChoice(code.getIsMultipleChoice());
                    one.setAttributeLimit(code.getAttributeLimit());
                    one.setAttributeValueMap(code.getAttributeValueMap());
                    String handleValue = ProductBaseHandler.handleAttributeValue(one);
                    rowMap.put(code.getAttributeCode(),handleValue );
                    if (Objects.equals("attachment", one.getAttributeCode()) && !StringUtils.isEmpty(value) && StringUtils.isEmpty(handleValue)) {
                        KingHoodExceptionUtil.throwException("请检查附件是否有效");
                    }
                } else {
                    // 系统字段
                    switch (code.getCode()) {
                        case "brand":
                            Long brandId = dao.getBrandMap().get(value);
                            rowMap.put("brandId", brandId == null ? null : brandId.toString());
                            break;
                        case "goods":
                            Long goodsId = dao.getGoodsMap().get(value);
                            rowMap.put("goodsId", goodsId == null ? null : goodsId.toString());
                            break;
                        case "category":
                            Long categoryId = dao.getCategoryMap().get(value);
                            rowMap.put("categoryId", categoryId == null ? null : categoryId.toString());
                            break;
                        case "status":
                            Integer status = ProductStatusEnums.getTypeByName(value);
                            rowMap.put(code.getCode(), status == null ? null : status.toString());
                            break;
                        case "skuCode":
                            if (StringUtils.isEmpty(value)) {
                                break;
                            }
                            rowMap.put(code.getCode(), value);
                            break;
                        case "skuStatus":
                            if (StringUtils.isEmpty(value)) {
                                break;
                            }
                            Integer skuStatus = ProductSkuStatusEnums.getTypeByName(value);
                            rowMap.put(code.getCode(), skuStatus == null ? null : skuStatus.toString());
                            break;
                        case "supplier":
                            if (StringUtils.isEmpty(value)) {
                                break;
                            }
                            Long supplierId = dao.getSupplierMap().get(value);
                            KingHoodExceptionUtil.isNull(supplierId,"请检查供应商是否有效");
                            rowMap.put("supplierId", supplierId == null ? null : supplierId.toString());
                            break;
                        default:
                    }

                }
            });
            if (!CollectionUtils.isEmpty(rowMap)) {
                res.add(rowMap);
            }
        }
        return res;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Map<Integer, String>> handleExcelData(List<Map<Integer, String>> cachedDataList,
                                                      Map<Integer, ProductExcelAttributeDTO> headCodeMap,
                                                      BaseProductDaoDTO dao,
                                                      RowFieldRecordDTO rowFieldRecord) {
        if (CollectionUtils.isEmpty(cachedDataList)) {
            return null;
        }
        log.info("开始处理excel数据");
        StopWatch w = new StopWatch();
        w.start("分析数据");

        List<ProductExcelRowDTO> rowList = ProductBaseHandler.handleExcelData(cachedDataList,headCodeMap,dao,rowFieldRecord);

        // 逐个商品解析excel数据
        List<ProductExcelDaoDTO> productDaoList = new ArrayList<>();
        Map<String, List<ProductExcelRowDTO>> productMap = rowList.stream()
                .filter(x->Objects.nonNull(x.getStyleNumber()))
                .collect(Collectors.groupingBy(ProductExcelRowDTO::getStyleNumber));
        productMap.values().forEach(x -> {
            try {
                ProductExcelDaoDTO productExcelDaoDTO = ProductBaseHandler.handleProductData(x, rowFieldRecord,dao);
                if (Objects.nonNull(productExcelDaoDTO)) {
                    productDaoList.add(productExcelDaoDTO);
                }
            } catch (KingHoodException kingHoodException){
                x.forEach(row -> {
                    int size = rowFieldRecord.getSize();
                    ExcelDataInfoDTO one = new ExcelDataInfoDTO();
                    one.setIndex(size);
                    one.setValue("导入失败");
                    one.setBad(true);
                    row.getMap().put(size, one);
                    ExcelDataInfoDTO two = new ExcelDataInfoDTO();
                    two.setIndex(size + 1);
                    two.setValue(kingHoodException.getMessage());
                    two.setBad(true);
                    row.getMap().put(size + 1, two);
                });
            } catch (Exception e) {
                log.error("导入发生异常：", e);
                x.forEach(row -> {
                    ProductBaseHandler.badData(row,"导入发生异常",rowFieldRecord.getSize());
                });
            }
        });

        w.stop();
        w.start("入库");
        // 入库
        saveProductDao(productDaoList);
        w.stop();
        log.info(w.prettyPrint());

        // 返回数据
        ArrayList<Map<Integer, String>> result = new ArrayList<>();
        for (ProductExcelRowDTO row : rowList) {
            HashMap<Integer, String> r = new HashMap<>();
            row.getMap().values().forEach(x -> {
                r.put(x.getIndex(), x.getValue());
            });
            result.add(r);
        }
        return result;
    }

    /**
     * 数据入库
     */
    private void saveProductDao(List<ProductExcelDaoDTO> productDaoList) {
        if (CollectionUtils.isEmpty(productDaoList)) {
            return;
        }
        List<ProductBaseDO> productBaseDOS = new ArrayList<>();
        List<ProductAttributeDO> attributes = new ArrayList<>();
        List<ProductSkuBaseDO> skuBaseList = new ArrayList<>();
        List<ProductSkuSupplierBaseDO> supplierBaseList = new ArrayList<>();
        List<ProductSkuExtrasBaseDO> extrasBaseList = new ArrayList<>();
        productDaoList.forEach(x -> {
            productBaseDOS.add(x.getProductBaseDO());
            attributes.addAll(x.getAttributes());
            skuBaseList.addAll(x.getSkuBaseList());
            supplierBaseList.addAll(x.getSupplierBaseList());
            extrasBaseList.addAll(x.getExtrasBaseList());
        });

        this.saveBatch(productBaseDOS);
        if(!CollectionUtils.isEmpty(attributes)){
            productAttributeService.saveBatch(attributes);
        }
        if(!CollectionUtils.isEmpty(skuBaseList)){
            productSkuBaseService.saveBatch(skuBaseList);
        }
        if(!CollectionUtils.isEmpty(supplierBaseList)){
            productSkuSupplierBaseService.saveBatch(supplierBaseList);
        }
        if(!CollectionUtils.isEmpty(extrasBaseList)){
            productSkuExtrasBaseService.saveBatch(extrasBaseList);
        }

        List<Long> productIdList = productBaseDOS.stream().map(ProductBaseDO::getId).collect(Collectors.toList());
        asyncBusinessLogService.addLogBusinessIdBatch(productIdList,
                null, BusinessLogOperateEnum.UPLOAD_STYLE.getType(), UserUtil.getUserId());

    }

    /**
     * 获取列表中存在的code
     *
     * @param productCodeList 产品代码列表
     * @author jp
     * @date 2023/12/28
     */
    @Override
    public List<String> getCodeByList(Set<String> productCodeList) {
        return this.baseMapper.getCodeByList(productCodeList);
    }

    /**
     * 新增时的配置信息
     *
     * @param param 参数
     * @author jp
     * @date 2023/12/28
     */
    @Override
    public ProductConfigVO getConfigInfo(ProductAddTypeDTO param) {
        ProductConfigVO productConfigVO = new ProductConfigVO();
        if (Objects.nonNull(param.getGoodsId())) {
            BaseGoodsDO goods = new LambdaQueryChainWrapper<>(goodsMapper)
                    .eq(BaseGoodsDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseGoodsDO::getStatus, CommonConstants.ENABLE)
                    .eq(BaseGoodsDO::getId, param.getGoodsId())
                    .one();
            if (Objects.nonNull(goods)) {
                productConfigVO.setGoodsId(goods.getId());
                productConfigVO.setGoodsName(goods.getNamePath().replaceAll("/", " > "));
                productConfigVO.setGoodsCode(goods.getGoodsCode());
                productConfigVO.setGoodsCodeName("[" + goods.getGoodsCode() + "]" + goods.getGoodsName());
            }
        }
        if (Objects.nonNull(param.getCategoryId())) {
            BaseCategoryDO category = new LambdaQueryChainWrapper<>(categoryMapper)
                    .eq(BaseCategoryDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseCategoryDO::getStatus, CommonConstants.ENABLE)
                    .eq(BaseCategoryDO::getId, param.getCategoryId())
                    .one();
            if (Objects.nonNull(category)) {
                productConfigVO.setCategoryId(category.getId());
                productConfigVO.setCategoryName(category.getNamePath().replaceAll("/", " > "));
                productConfigVO.setCategoryCode(category.getCategoryCode());
                productConfigVO.setCategoryCodeName("[" + category.getCategoryCode() + "]" + category.getCategoryName());
            }
        }
        if (Objects.nonNull(param.getBrandId())) {
            BaseBrandDO brand = new LambdaQueryChainWrapper<>(brandMapper)
                    .eq(BaseBrandDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseBrandDO::getStatus, CommonConstants.ENABLE)
                    .eq(BaseBrandDO::getId, param.getBrandId())
                    .one();
            if (Objects.nonNull(brand)) {
                productConfigVO.setBrandId(brand.getId());
                productConfigVO.setBrandName(brand.getBrandName());
                productConfigVO.setBrandCode(brand.getBrandCode());
                productConfigVO.setBrandCodeName("[" + brand.getBrandCode() + "]" + brand.getBrandName());
            }
        }
        if (Objects.nonNull(param.getAttributeValueId())) {
            BaseAttributeValueDO attributeValue = new LambdaQueryChainWrapper<>(attributeValueMapper)
                    .eq(BaseAttributeValueDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .eq(BaseAttributeValueDO::getStatus, CommonConstants.ENABLE)
                    .eq(BaseAttributeValueDO::getId, param.getAttributeValueId())
                    .one();
            if (Objects.nonNull(attributeValue)) {
                productConfigVO.setAttributeValueId(attributeValue.getId());
                productConfigVO.setAttributeValue(attributeValue.getValue());
                productConfigVO.setAttributeValueCode(attributeValue.getCode());
                productConfigVO.setAttributeCodeValue("[" + attributeValue.getCode() + "]" + attributeValue.getValue());
            }
        }
        return productConfigVO;
    }

    /**
     * 删除
     *
     * @param id id
     * @author jp
     * @date 2023/12/29
     */
    @Override
    public void delProduct(Long id) {
        this.lambdaUpdate().set(ProductBaseDO::getIsDelete, CommonConstants.IS_DELETE_Y)
                .set(ProductBaseDO::getUpdateTime, LocalDateTime.now())
                .set(ProductBaseDO::getUpdateUserId, UserUtil.getUserId())
                .eq(ProductBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .eq(ProductBaseDO::getId, id)
                .update();
        productSkuBaseService.lambdaUpdate().set(ProductSkuBaseDO::getIsDelete, CommonConstants.IS_DELETE_Y)
                .set(ProductSkuBaseDO::getUpdateTime, LocalDateTime.now())
                .set(ProductSkuBaseDO::getUpdateUserId, UserUtil.getUserId())
                .eq(ProductSkuBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .eq(ProductSkuBaseDO::getProductId, id)
                .update();
    }

    /**
     * 更新产品状态
     *
     * @param param 参数
     * @author jp
     * @date 2023/12/29
     */
    @Override
    public void updateProductStatus(StatusRemarkReqDTO param) {
        List<ProductBaseDO> productBaseDOList = this.lambdaQuery()
                .eq(ProductBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .in(ProductBaseDO::getId, param.getIdList())
                .list();
        this.lambdaUpdate().set(ProductBaseDO::getStatus, param.getStatus())
                .set(ProductBaseDO::getUpdateUserId, UserUtil.getUserId())
                .set(ProductBaseDO::getUpdateTime, LocalDateTime.now())
                .eq(ProductBaseDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .in(ProductBaseDO::getId, param.getIdList())
                .update();
        // 加入日志
        for (ProductBaseDO productBaseDO : productBaseDOList) {
            String conent = String.format("状态：从[%s]变更为[%s]", ProductStatusEnums.getNameByType(productBaseDO.getStatus()),
                    ProductStatusEnums.getNameByType(param.getStatus()));
            if (!StringUtils.isEmpty(param.getRemark())) {
                conent = conent + "；备注：" + param.getRemark();
            }
            asyncBusinessLogService.addLog(null, productBaseDO.getId(), conent,
                    BusinessLogOperateEnum.UPDATE_STATUS.getType(), UserUtil.getUserId());
        }
    }

    /**
     * 添加标签
     *
     * @param param 参数
     * @author jp
     * @date 2024/01/03
     */
    @Override
    public void addLabel(ProductLabelReqDTO param) {
        List<ProductSkuLabelRelateDO> productSkuLabelRelateDOList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        for (Long p : param.getProductIdList()) {
            String content = "新增：";
            List<String> labelTxt = new ArrayList<>();
            Map<Long, BaseLabelItemDO> itemMap = baseLabelItemService.lambdaQuery()
                    .eq(BaseLabelItemDO::getIsDelete, CommonConstants.IS_DELETE_N)
                    .in(BaseLabelItemDO::getId, param.getItemIdList())
                    .list().stream().collect(Collectors.toMap(BaseLabelItemDO::getId, i -> i, (k1, k2) -> k1));
            for (Long itemId : param.getItemIdList()) {
                ProductSkuLabelRelateDO productLabelRelate = productSkuLabelRelateService.lambdaQuery()
                        .eq(ProductSkuLabelRelateDO::getProductId, p)
                        .eq(ProductSkuLabelRelateDO::getLabelId, itemMap.get(itemId).getLabelId())
                        .eq(ProductSkuLabelRelateDO::getLabelItemId, itemId)
                        .eq(ProductSkuLabelRelateDO::getIsDelete, CommonConstants.IS_DELETE_N)
                        .one();
                if (Objects.isNull(productLabelRelate)) {
                    productLabelRelate = new ProductSkuLabelRelateDO();
                    productLabelRelate.setId(IdGenUtil.getId())
                            .setProductId(p)
                            .setLabelId(itemMap.get(itemId).getLabelId())
                            .setLabelItemId(itemId)
                            .setCreateTime(now)
                            .setCreateUserId(UserUtil.getUserId());
                }
                productLabelRelate.setStartTime(param.getStartTime())
                        .setEndTime(param.getEndTime())
                        .setUpdateTime(now)
                        .setUpdateUserId(UserUtil.getUserId());
                productSkuLabelRelateDOList.add(productLabelRelate);
                labelTxt.add(itemMap.get(itemId).getItemValue());
            }
            content = content + String.join(",", labelTxt);
            asyncBusinessLogService.addLog(null, p, content,
                    BusinessLogOperateEnum.SET_LABEL.getType(), UserUtil.getUserId());
        }
        productSkuLabelRelateService.saveOrUpdateBatch(productSkuLabelRelateDOList);
    }

    /**
     * 获取产品标签
     *
     * @param param 参数
     * @return @return {@link Object }
     * @author jp
     * @date 2024/01/12 16:16
     */
    @Override
    public Object getProductLabel(ProductLabelListReqDTO param) {
        List<ProductLabelVO> result = this.baseMapper.getProductLabel(param);

        Set<Long> userIdList = new HashSet<>();
        for (ProductLabelVO record : result) {
            userIdList.add(record.getCreateUserId());
            userIdList.add(record.getUpdateUserId());
        }
        userIdList.remove(null);
        if (!CollectionUtils.isEmpty(userIdList)) {
            Map<Long, UserRemoteVo> userMap = userRemote.getUserByIds(new ArrayList<>(userIdList));
            for (ProductLabelVO record : result) {
                record.setCreateUserName(UserNameUtil.getName(record.getCreateUserId(), userMap));
                record.setUpdateUserName(UserNameUtil.getName(record.getUpdateUserId(), userMap));
            }
        }

        DirectionReqRemoteDTO directionReqRemoteDTO = new DirectionReqRemoteDTO();
        List<String> codeList = new ArrayList<>();
        codeList.add("label_type");
        directionReqRemoteDTO.setDataCodeList(codeList);
        List<DirectionRemoteVO> directionRemoteList = directionRemote.getDirectionByCodeList(directionReqRemoteDTO);
        Map<String, DirectionRemoteVO> labelTypeMap = null;
        if (!CollectionUtils.isEmpty(directionRemoteList)) {
            labelTypeMap = directionRemoteList.stream().collect(Collectors.toMap(DirectionRemoteVO::getDataKey, i -> i, (x,y) -> x));
            for (ProductLabelVO record : result) {
                // 设置标签类型
                if (Objects.nonNull(labelTypeMap)) {
                    record.setLabelTypeName(labelTypeMap.get(String.valueOf(record.getLabelTypeId())).getDataValue());
                }
            }
        }
        return result;
    }

    /**
     * 删除产品标签
     *
     * @param id 身份证件
     * @return
     * @author jp
     * @date 2024/01/12 16:16
     */
    @Override
    public void delProductLabel(Long id) {
        ProductSkuLabelRelateDO productSkuLabelRelateDO = productSkuLabelRelateService.getById(id);
        String value = this.baseMapper.getLabelValue(id);
        productSkuLabelRelateService.lambdaUpdate().set(ProductSkuLabelRelateDO::getIsDelete, CommonConstants.IS_DELETE_Y)
                .set(ProductSkuLabelRelateDO::getUpdateTime, LocalDateTime.now())
                .set(ProductSkuLabelRelateDO::getUpdateUserId, UserUtil.getUserId())
                .eq(ProductSkuLabelRelateDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .eq(ProductSkuLabelRelateDO::getId, id)
                .update();
        asyncBusinessLogService.addLog(null, productSkuLabelRelateDO.getProductId(), "移除："+value,
                BusinessLogOperateEnum.SET_LABEL.getType(), UserUtil.getUserId());
    }

    /**
     * 修改产品标签时间
     *
     * @param newData 参数
     * @return
     * @author jp
     * @date 2024/01/12 16:16
     */
    @Override
    public void updateProductLabelTime(ProductLabelReqDTO newData) {
        ProductSkuLabelRelateDO oldData = productSkuLabelRelateService.getById(newData.getId());
        productSkuLabelRelateService.lambdaUpdate()
                .set(ProductSkuLabelRelateDO::getStartTime, newData.getStartTime())
                .set(ProductSkuLabelRelateDO::getEndTime, newData.getEndTime())
                .set(ProductSkuLabelRelateDO::getUpdateTime, LocalDateTime.now())
                .set(ProductSkuLabelRelateDO::getUpdateUserId, UserUtil.getUserId())
                .eq(ProductSkuLabelRelateDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .eq(ProductSkuLabelRelateDO::getId, newData.getId())
                .update();
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String t1 = Objects.nonNull(oldData.getStartTime()) ? dtf2.format(oldData.getStartTime()) : "空";
        String t2 = Objects.nonNull(newData.getStartTime()) ? dtf2.format(newData.getStartTime()) : "空";
        String t3 = Objects.nonNull(oldData.getEndTime()) ? dtf2.format(oldData.getEndTime()) : "空";
        String t4 = Objects.nonNull(newData.getEndTime()) ? dtf2.format(newData.getEndTime()) : "空";
        String content = String.format("打标开始时间从%s改为%s,打标结束时间从%s改为%s", t1, t2, t3, t4)
                .replaceAll("null","空");
        asyncBusinessLogService.addLog(null, oldData.getProductId(), content,
                BusinessLogOperateEnum.SET_LABEL.getType(), UserUtil.getUserId());
    }

    /**
     * 获取产品属性
     *
     * @return @return {@link List }<{@link AttributeValueVO }>
     * @author jp
     * @date 2024/01/15 15:54
     */
    @Override
    public List<AttributeNameVO> getProductFields(String businessCode) {
        List<AttributeNameVO> result = new ArrayList<>();
        result.add(new AttributeNameVO("styleInfo", 0,"款式信息"));
        result.add(new AttributeNameVO("brandName", 0,"品牌名称"));
        result.add(new AttributeNameVO("goodsName", 0,"货类"));
        result.add(new AttributeNameVO("categoryName",0,"品类"));
        result.add(new AttributeNameVO("statusTxt", 0,"状态"));
        List<AttributeNameVO> attributeList = this.baseMapper.getProductAttribute();
        attributeList.forEach(i -> i.setCodeType(1));
        result.addAll(attributeList);
        // 要求这几个字段放在最后展示
        result.add(new AttributeNameVO("createUserName",0, "创建人"));
        result.add(new AttributeNameVO("createTime", 0,"创建时间"));
        result.add(new AttributeNameVO("updateTime",0, "最后修改时间"));
        result.add(new AttributeNameVO("updateUserName", 0,"最后操作人"));

        GetUserSearchSettingReqDTO settingReqDTO = new GetUserSearchSettingReqDTO();
        settingReqDTO.setBusinessType(2);
        settingReqDTO.setBusinessCode(businessCode);
        GetUserSearchSettingVO res = userSearchSettingService.getUserSearchSetting(settingReqDTO);
        if (Objects.nonNull(res) && !CollectionUtils.isEmpty(res.getShowList())) {
            Map<String, String> codeMap = res.getShowList().stream().collect(Collectors.toMap(SearchSettingVO::getCode, SearchSettingVO::getCode, (x, y) -> x));
            for (AttributeNameVO field : result) {
                String code = codeMap.get(field.getCode());
                if (!StringUtils.isEmpty(code)) {
                    field.setIsShow(true);
                }
            }
        } else {
            // 没有配置，给系统值设置默认值
            result.stream().filter(i -> i.getCodeType() == 0).forEach(i -> i.setIsShow(true));
        }
        return result;
    }

    /**
     * 获取产品搜索字段
     *
     * @return @return {@link List }<{@link AttributeNameVO }>
     * @author jp
     * @date 2024/01/17 20:26
     */
    @Override
    public List<AttributeNameVO> getProductSearchFields(String businessCode) {
        List<AttributeNameVO> result = new ArrayList<>();
        result.add(new AttributeNameVO("styleName", 0,"款式名称"));
        result.add(new AttributeNameVO("styleNumber", 0,"款号"));
        result.add(new AttributeNameVO("brandList", 0,"品牌名称"));
        result.add(new AttributeNameVO("goodsList",0,"货类"));
        result.add(new AttributeNameVO("categoryList",0, "品类"));
        result.add(new AttributeNameVO("labelList", 0,"标签"));
        result.add(new AttributeNameVO("createTime",0, "创建时间"));

        List<AttributeNameVO> attributeList = this.baseMapper.getProductAttribute();
        AttributeCodesReqDTO attributeCodesReqDTO = new AttributeCodesReqDTO();
        attributeCodesReqDTO.setCodes(attributeList.stream().map(AttributeNameVO::getCode).collect(Collectors.toList()));
        // 查询属性数据
        List<AttributeReqDTO> attList = baseAttributeService.attributeByCodes(attributeCodesReqDTO);
        Map<String, AttributeReqDTO> attMap = attList.stream().collect(Collectors.toMap(AttributeReqDTO::getAttributeCode, i -> i, (x,y) -> x));
        attributeList.forEach(i -> {
            i.setCodeType(1);
            if (attMap.containsKey(i.getCode())) {
                i.setAttributeInfo(attMap.get(i.getCode()));
            }
        });
        result.addAll(attributeList);

        GetUserSearchSettingReqDTO settingReqDTO = new GetUserSearchSettingReqDTO();
        settingReqDTO.setBusinessType(1);
        settingReqDTO.setBusinessCode(businessCode);
        GetUserSearchSettingVO res = userSearchSettingService.getUserSearchSetting(settingReqDTO);
        if (Objects.nonNull(res) && !CollectionUtils.isEmpty(res.getSearchList())) {
            Map<String, String> codeMap = res.getSearchList().stream().collect(Collectors.toMap(SearchSettingVO::getCode, SearchSettingVO::getCode, (x, y) -> x));
            for (AttributeNameVO field : result) {
                String code = codeMap.get(field.getCode());
                if (!StringUtils.isEmpty(code)) {
                    field.setIsShow(true);
                }
            }
        } else {
            // 没有配置，给系统值设置默认值
            result.stream().filter(i -> i.getCodeType() == 0).forEach(i -> i.setIsShow(true));
        }

        return result;
    }

    @Override
    public GetSkuRelateIdDTO getSkuRelateId(Long productId, String skuCode) {
        return this.getBaseMapper().getSkuRelateId(productId,skuCode);
    }

    @Override
    public List<BaseProductDTODO> getProductInfo(GetProductInfoReqDTO in) {
        return null;
    }
}
